<template>
  <view class="withdrawal-container">
    <view class="header">
      <view class="back-btn" @click="goBack">
        <text class="back-arrow">←</text>
      </view>
      <text class="title">提现申请</text>
    </view>
    
    <!-- 支付方式选择 -->
    <view class="payment-method">
      <view class="method-item" :class="{ active: selectedMethod === 'alipay' }" @click="selectedMethod = 'alipay'">
        <text class="payment-text">支付宝</text>
      </view>
      <view class="method-item" :class="{ active: selectedMethod === 'wechat' }" @click="selectedMethod = 'wechat'">
        <text class="payment-text">微信</text>
      </view>
    </view>
    
    <!-- 输入表单 -->
    <view class="form-section">
      <!-- 支付宝账号 -->
      <view v-if="selectedMethod === 'alipay'" class="form-item">
        <text class="form-label">支付宝账号：</text>
        <input type="text" class="form-input" placeholder="请输入支付宝账号" v-model="alipayAccount"/>
      </view>
      
      <!-- 姓名 -->
      <view v-if="selectedMethod === 'alipay'" class="form-item">
        <text class="form-label">姓名：</text>
        <input type="text" class="form-input" placeholder="请输入姓名" v-model="name"/>
      </view>
      
      <!-- 微信手机号 -->
      <view v-if="selectedMethod === 'wechat'" class="form-item">
        <text class="form-label">手机号：</text>
        <input type="number" class="form-input" placeholder="请输入手机号" v-model="wechatPhone"/>
      </view>
      
      <!-- 提现金额 -->
      <view class="form-item">
        <text class="form-label">提现金额：</text>
        <input type="number" class="form-input" placeholder="请输入提现金额" v-model="amount" />
        <text class="max-amount">最大可提{{userInfo.balance}}元</text>
      </view>
      
      <!-- 上传收款码 -->
      <view class="form-item">
        <text class="form-label">收款码：</text>
        <view class="upload-section">
          <view v-if="!receiptCodeUrl" class="upload-btn" @click="uploadReceiptCode">
            <text class="upload-text">点击上传收款码</text>
          </view>
          <view v-else class="receipt-image-container">
            <image :src="receiptCodeUrl" mode="aspectFit" class="receipt-image"></image>
            <view class="delete-btn" @click="deleteReceiptCode">
              <text class="delete-text">删除</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 提现按钮 -->
    <view class="button-section">
      <button class="withdrawal-button" @click="handleWithdrawal">立即提现</button>
    </view>

  </view>
</template>

<script>
import { API_CONFIG } from '../../utils/config.js'
import { post, uploadFile } from '../../utils/request.js'

export default {
  data() {
    return {
      selectedMethod: 'alipay', // 选中的提现方式：alipay或wechat
      alipayAccount: '',
      name: '',
      wechatPhone: '',
      amount: '',
      maxAmount: '3151.43',
      receiptCodeUrl: '', // 收款码图片URL
      receiptCodeFile: null, // 收款码文件
      userInfo: uni.getStorageSync('userInfo')
    }
  },
  
  onLoad() {
    // 页面加载时的逻辑
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 上传收款码
    uploadReceiptCode() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0]
          this.receiptCodeFile = tempFilePath
          this.receiptCodeUrl = tempFilePath
          
          // 上传图片到服务器
          this.uploadFileToServer(tempFilePath)
        }
      })
    },
    
    // 删除收款码
    deleteReceiptCode() {
      this.receiptCodeUrl = ''
      this.receiptCodeFile = null
    },
    
    // 上传文件到服务器
    async uploadFileToServer(filePath) {
      try {
        uni.showLoading({ title: '上传中...' })
        
        // 使用公共的uploadFile方法上传文件
        const data = await uploadFile(filePath)
        
        uni.hideLoading()
        
        console.log(data)
        if (data.code === 0) {
          // 上传成功，保存文件路径或URL
          if (data.data && data.data.fileUrl) {
            this.receiptCodeUrl = data.data.fileUrl
          }
        } else {
          uni.showToast({
            title: data.msg || '上传失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        
        if (error.message === '请先登录') {
          uni.showToast({
            title: error.message,
            icon: 'none'
          })
          return
        }
        
        uni.showToast({
          title: '网络异常，请稍后再试',
          icon: 'none'
        })
        console.error('上传收款码失败:', error)
      }
    },
    
    // 处理提现申请
    handleWithdrawal() {
      // 验证输入
      if (this.selectedMethod === 'alipay') {
        if (!this.alipayAccount) {
          uni.showToast({
            title: '请输入支付宝账号',
            icon: 'none'
          })
          return
        }
        
        if (!this.name) {
          uni.showToast({
            title: '请输入姓名',
            icon: 'none'
          })
          return
        }
      } else if (this.selectedMethod === 'wechat') {
        if (!this.wechatPhone) {
          uni.showToast({
            title: '请输入手机号',
            icon: 'none'
          })
          return
        }
        
        // 简单的手机号格式验证
        const phoneRegex = /^1[3-9]\d{9}$/
        if (!phoneRegex.test(this.wechatPhone)) {
          uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none'
          })
          return
        }
      }
      
      if (!this.amount || parseFloat(this.amount) <= 0 || parseFloat(this.amount) > this.userInfo.balance) {
        uni.showToast({
          title: '请输入有效金额',
          icon: 'none'
        })
        return
      }
      
      if (parseFloat(this.amount) > parseFloat(this.maxAmount)) {
        uni.showToast({
          title: '提现金额不能超过最大可提金额',
          icon: 'none'
        })
        return
      }
      
      if (!this.receiptCodeUrl) {
        uni.showToast({
          title: '请上传收款码',
          icon: 'none'
        })
        return
      }
      
      // 显示确认弹窗
      const confirmContent = this.selectedMethod === 'alipay' 
        ? `您确定要提现${this.amount}元到支付宝账号${this.alipayAccount}吗？`
        : `您确定要提现${this.amount}元到微信账号吗？`
      
      uni.showModal({
        title: '确认提现',
        content: confirmContent,
        success: (res) => {
          if (res.confirm) {
            // 提交提现申请
            this.submitWithdrawal()
          }
        }
      })
    },
    
    // 提交提现申请
    async submitWithdrawal() {
      try {
        const token = uni.getStorageSync('token')
        if (!token) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
          return
        }
        
        uni.showLoading({ title: '处理中...' })
        
        // 1. 先调用更新提现信息接口
        const updateCashData = {
          name: this.selectedMethod === 'alipay' ? this.name : '',
          account: this.selectedMethod === 'alipay' ? this.alipayAccount : this.wechatPhone,
          payeeCode: this.receiptCodeUrl
        }
        
        const updateRes = await post(API_CONFIG.API.UPDATE_CASH, updateCashData)
        
        if (updateRes.code !== 0) {
          uni.hideLoading()
          uni.showToast({
            title: updateRes.msg || '更新提现信息失败',
            icon: 'none'
          })
          return
        }
        
        // 2. 再调用提现申请接口
        const applyData = {
          money: parseFloat(this.amount)
        }
        
        const applyRes = await post(API_CONFIG.API.CASH_APPLY, applyData)
        
        uni.hideLoading()
        
        if (applyRes.code === 0) {
          uni.showToast({
            title: '提现申请提交成功',
            icon: 'success'
          })
          
          // 跳转到资金明细页面
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/financial-detail/financial-detail'
            })
          }, 1500)
        } else {
          uni.showToast({
            title: applyRes.msg || '提现申请失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '网络异常，请稍后再试',
          icon: 'none'
        })
        console.error('提现申请失败:', error)
      }
    }
  }
}</script>

<style scoped>
.withdrawal-container {
  background-color: #3A3052;
  min-height: 100vh;
  padding-bottom: 120rpx;
}


.header {
  background-color: #4A4062;
  padding: 10px 65px 10px 15px;
  display: flex;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-btn {
  width: 40px;
  height: 40px;
  background-color: rgba(240, 217, 181, 0.1);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.back-btn:active {
  background-color: rgba(240, 217, 181, 0.2);
  transform: scale(0.95);
}

.back-arrow {
  color: #F0D9B5;
  font-size: 20px;
  font-weight: bold;
}

.title {
  flex: 1;
  color: rgba(255, 255, 255, 0.5);
  font-size: 16px;
  font-weight: 600;
  text-align: center;
}

.payment-method {
  padding: 30rpx;
  display: flex;
  gap: 20rpx;
}

.method-item {
  background-color: #4A4062;
  border-radius: 16rpx;
  padding: 25rpx 40rpx;
  display: flex;
  align-items: center;
  border: 2rpx solid #5A5072;
  flex: 1;
  justify-content: center;
}

.method-item.active {
  border-color: #F0D9B5;
  background-color: #5A5072;
}

.payment-icon {
  width: 50rpx;
  height: 50rpx;
  margin-right: 20rpx;
}

.payment-text {
  color: #FFFFFF;
  font-size: 32rpx;
  flex: 1;
}

.check-icon {
  width: 36rpx;
  height: 36rpx;
}

.form-section {
  padding: 0 30rpx 30rpx;
}

.form-item {
  background-color: #4A4062;
  border-radius: 16rpx;
  padding: 25rpx;
  margin-bottom: 20rpx;
}

.form-label {
  color: #F0D9B5;
  font-size: 32rpx;
  margin-bottom: 15rpx;
  display: block;
}

.form-input {
  color: #FFFFFF;
  font-size: 32rpx;
  background-color: transparent;
  border: none;
  width: 100%;
}

.form-input::placeholder {
  color: #8F82A8;
  font-size: 32rpx;
}

.max-amount {
  color: #8F82A8;
  font-size: 28rpx;
  display: block;
  margin-top: 10rpx;
}

.upload-section {
  margin-top: 10rpx;
}

.upload-btn {
  background-color: #5A5072;
  border-radius: 12rpx;
  padding: 30rpx;
  text-align: center;
  border: 2rpx dashed #8F82A8;
}

.upload-text {
  color: #8F82A8;
  font-size: 28rpx;
}

.receipt-image-container {
  position: relative;
  width: 100%;
  max-width: 400rpx;
  margin: 0 auto;
}

.receipt-image {
  width: 100%;
  height: 400rpx;
  border-radius: 12rpx;
}

.delete-btn {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  background-color: rgba(0, 0, 0, 0.6);
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
}

.delete-text {
  color: #FFFFFF;
  font-size: 24rpx;
}

.button-section {
  padding: 0 30rpx 40rpx;
}

.withdrawal-button {
  background-color: #F8E7D0;
  color: #3A3052;
  font-size: 36rpx;
  font-weight: bold;
  padding: 25rpx;
  border-radius: 16rpx;
  border: none;
  width: 100%;
}

.withdrawal-button:active {
  transform: scale(0.98);
  opacity: 0.9;
}

.rules-section {
  padding: 0 30rpx;
}

.rules-title {
  color: #FFFFFF;
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
}

.rules-content {
  background-color: #4A4062;
  border-radius: 16rpx;
  padding: 25rpx;
}

.rule-text {
  color: #8F82A8;
  font-size: 28rpx;
  line-height: 1.6;
  display: block;
  margin-bottom: 15rpx;
}

.rule-text:last-child {
  margin-bottom: 0;
}

.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background-color: #2A2240;
  display: flex;
  justify-content: space-around;
  align-items: center;
  border-top: 1rpx solid #3A3052;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #8F82A8;
}

.nav-item.active {
  color: #F0D9B5;
}

.nav-item image {
  width: 50rpx;
  height: 50rpx;
  margin-bottom: 10rpx;
}

.nav-item text {
  font-size: 24rpx;
}
</style>